class Resource < ActiveRecord::Base
  has_many :assignments

  def name
    Resource.normalize_name(read_attribute(:name))
  end

  def Resource.normalize_name(value)
    value.downcase
  end

  def Resource.format_name(value)
    value.titlecase
  end

  def Resource.names
    find(:all).collect { |resource| resource.name }
  end

  # Returns a collection of resource objects that correspond to the
  # resource names. If any of the resources are not found in the db
  # then they are created automatically.
  def Resource.resources(resource_names)
    all_resources = Resource.find(:all)

    resource_names.collect do |resource_name|

      # first try to find an existing resource that matches
      resource = all_resources.find do |resource|
        resource.name == Resource.normalize_name(resource_name)
      end
      
      # otherwise, create a new resource
      resource || Resource.new(:name => resource_name)
    end
  end
end
